package com.lge.remoteshot.network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import android.util.Log;

import com.lge.remoteshot.camera.CameraActivity;

public class ServerActionThread extends Thread {
	private CameraActivity activity;

	private ServerSocket serverSock;
	private Socket sock;
	private InputStream is;
	private OutputStream os;

	private byte[] buffer = new byte[128];

	public ServerActionThread(CameraActivity activity) {
		// TODO Auto-generated constructor stub
		this.activity = activity;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			serverSock = new ServerSocket(ServerManager.SERVER_ACTION_PORT);
			sock = serverSock.accept();
			os = sock.getOutputStream();
			is = sock.getInputStream();
			Log.d(CameraActivity.TAG, "ServerActionThread:run:is,os created");
			int read = 0;
			while ((read = is.read(buffer)) != -1) {
				String msg = new String(buffer, 0, read);
				Log.d(CameraActivity.TAG, "ServerActionThread:run:receive msg" + msg);
				activity.setReceivedAction(msg);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Log.d(CameraActivity.TAG,
					"serverActionThread:run:IOException" + e.toString() + e.getMessage());
		} finally {
			try {
				if (is != null)
					is.close();
				if (os != null)
					os.close();
				if (sock != null)
					sock.close();
				if (serverSock != null)
					serverSock.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				Log.d(CameraActivity.TAG,
						"serverActionThread:run:finally:IOException" + e.toString()
								+ e.getMessage());
			}
		}
	}

	public void sendAction(String action) {
		// debug
		Log.d(CameraActivity.TAG, "serverActionThread:sendAction : " + action);
		if (os != null) {
			try {
				os.write(action.getBytes());
				os.flush();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				Log.d(CameraActivity.TAG,
						"serverActionThread:sendAction:IOException" + e.toString() + e.getMessage());
			}
		}
	}

	public void stopThread() {
		try {
			if (is != null)
				is.close();
			if (os != null)
				os.close();
			if (sock != null)
				sock.close();
			if (serverSock != null)
				serverSock.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Log.d(CameraActivity.TAG, "serverActionThread:stopThread:IOException" + e.toString()
					+ e.getMessage());
		}
	}
}